<template>
  <div class="question-type clearfix">
    <div class="oe-paper-top">
      <div class="oe-top-left"></div>
      <div class="oe-top-title">- {{ title }}-</div>
      <div class="oe-top-right"></div>
    </div>
    <div class="test-paper-content">
      <div class="paper-content-top clearfix">
        <div class="fl" v-if="curType">
          <span class="set-ruleEdit-label">随机试卷份数：</span>
          <a-input-number :min="1" :max="50" v-model="paperNumber" />
          <a-tooltip
            overlayClassName="tooltip-style"
            placement="bottom"
            title="从题目中随机选题生成n套试卷，学生作答从n套中随机抽取试卷，最多能生成50套。"
            :getPopupContainer="getPopupContainer"
          >
            <span class="set-ruleEdit-label" style="margin-left: 10px;">
              <a-icon type="question-circle" />
            </span>
          </a-tooltip>
        </div>
        <div class="fr">
          <span class="set-ruleEdit-label">考试总分：</span>
          <span class="set-content-label">{{ totalScore }}</span>
          <span class="set-ruleEdit-label" v-if="curType">（总分需为{{ examScore }}分）</span>
        </div>
      </div>
      <div v-for="(list, index) in ruleDataList" :key="index">
        <div class="paper-content-mess">
          <div>
            <span class="set-ruleEdit-label">题目分类：</span>
            <a-row style="width: calc(100% - 90px);display: inline-block;">
              <a-col :span="3" class="type-label-col">
                <span class="set-paper-lis">{{ list.Name }}</span>
              </a-col>
            </a-row>
          </div>
          <div class="paper-content-mess">
            <span class="set-ruleEdit-label">难度：</span>
            <a-checkbox-group v-model="list.defficultys" @change="onChangeState(list, index)">
              <a-checkbox :disabled="disabled" v-for="(item, index) in difficulty" :key="index" :value="item.value">
                {{ item.label }}
              </a-checkbox>
            </a-checkbox-group>
          </div>
          <div style="margin-top: 10px;">
            <span class="set-ruleEdit-label">知识点：</span>
            <a-button type="primary" :disabled="disabled" @click="getKnowledgeShow(list, index)">{{list.Name}}</a-button>
            <!-- <a-checkbox-group v-model="list.knowledgeIds" @change="onChangeState(list, index)">
              <a-checkbox
                :disabled="disabled"
                v-for="(item, index) in list.ruleKnowledgeList"
                :key="index"
                :value="item.id"
              >
                {{ item.name }}
              </a-checkbox>
            </a-checkbox-group> -->
          </div>
        </div>
        <div class="paper-type-num clearfix">
          <div
            class="paper-num-lis fl"
            v-for="(item, index) in list.data"
            :key="index"
          >
            <div class="paper-num-title">
              <div class="paper-top-title">
                <span class="big-title">{{ item.title }}</span>
                <span class="sub-title">{{ item.subTitle }}</span>
              </div>
              <div class="paper-top-right"></div>
            </div>
            <div class="paper-num-set clearfix">
              <div class="paper-label-box-number fl">
                <span class="paper-label-num">题目数量</span>
                <div>
                  <a-input-number
                    class="a-number-style"
                    :min="0"
                    :max="item.count"
                    :disabled="disabled"
                    step="1"
                    v-model="item.randomQuesNumber"
                    @change="(e) => onChangeNumber(e, index, list.Id)"
                  /><span style="min-width:20px;">/{{ item.count }}</span>
                </div>
              </div>
              <div class="paper-label-box fl">
                <span class="paper-label-num">每题分数</span>
                <div>
                  <a-input-number
                    class="a-number-style"
                    :min="0"
                    max="100"
                    :disabled="disabled"
                    step="1"
                    v-model="item.randomQuesScore"
                    @change="(e) => onChangeScore(e, index, list.Id)"
                  />
                </div>
              </div>
              <div class="paper-label-box fl">
                <span class="paper-label-num">题目总分</span>
                <div style="line-height: 32px;">{{ item.total }}分</div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <blank-tips v-if="ruleDataList.length < 1" content="请选择题目分类" />
      <div class="test-paper-btn" v-if="!isShowBtn">
        <a-button type="primary" :disabled="isCanEdit" @click="onSave">{{ saveTitle }}</a-button>
        <a-button :disabled="isCanEdit" @click="onCancel">{{ cancelTitle }}</a-button>
      </div>
    </div>
    <a-modal
      title="温馨提示"
      :visible="visible"
      :confirm-loading="confirmLoading"
      @ok="onHintOk"
      @cancel="visible = false"
    >
      <p>切换筛选条件时，会清空已设置的题目规则，您确定继续此次操作吗！</p>
    </a-modal>
    <a-modal v-model="knowledgeShow" title="知识点选择" @cancel="cancelKnowledge" @ok="onChangeKnowledge">
      <div style="height: 400px;overflow: auto;">
        <tree-select ref="tree" :width="'100%'" v-if="knowledgeShow" :know="knowList" :list="treeList"></tree-select>
      </div>
    </a-modal>
  </div>
</template>

<script>
import blankTips from '@/components/blank-tips/index.vue';
import treeSelect from '@/components/treeSelect/index.vue';
export default {
  name: 'qustionType',
  components: {
    blankTips,
    treeSelect
  },
  data() {
    return {
      // questionType 题目类型 1.单选题(客观),2.多选题(客观),3.判断(客观),5.填空题(主观),6.问答题(主观),7.匹配题(客观),8.阅读理解(客观),9.完形填空(客观),10.文件作答题(主观),11.视听题(客观)
      // questionType 题目类型 randomQuesNumber 选择题目个数 randomQuesScore 分数, courseId 题目分类Id, onLineKnowledgeIds 知识点Id, onLineKnowledgeTitles 知识点title, defficultys 难度类型
      totalScore: 0,
      visible: false,
      treeList: [],
      knowList: [],
      knowledgeShow: false,
      mode: 1,
      knowledge: '',
      ruleDataList: [],
      knowledgeList: [],
      knowledgeIndex: undefined,
      difficulty: [
        { value: 1, label: '非常简单' },
        { value: 2, label: '简单' },
        { value: 3, label: '一般' },
        { value: 4, label: '困难' },
        { value: 5, label: '非常困难' }
      ],
      temporaryList: [],
      temporaryIndex: null
    };
  },
  props: {
    courseNameList: { // 组件数据（一题目分类为基点实现数组循环出题）
      type: Array
    },
    title: { // 组件标题
      type: String,
      default: '标题'
    },
    saveTitle: {  // 确定按钮标题
      type: String,
      default: '保存'
    },
    cancelTitle:{
      type: String,
      default: '取消'
    },
    listeningTrigger: { // 深度监听触发装置（数组内部数据修改是触发，同步到组件）
      type: Boolean
    },
    disabled: {  // 试卷规则禁止修改类容可以保存
      type: Boolean,
      default: false
    },
    isCanEdit: {  // 试卷已启用禁止编辑按钮禁止点击
      type: Boolean,
      default: false
    },
    isShowBtn: {  // 试卷只读权限无法不显示按钮
      type: Boolean,
      default: false
    },
    curType: { // 当前组件类型 (true 试卷类型 false 规则类型)
      type: Boolean,
      default: true
    },
    paperNumber: {  // 试卷份数
      type: String
    },
    examScore: {  // 试卷规则分数（后台返回的值）
      type: Number,
      default: null
    }
  },
  computed: {
    courseId: function() { // 提取题目分类Id
      return this.courseNameList.map((v) => {
        return v.Id;
      });
    }
  },
  watch: {
    ruleDataList: {
      handler: function(newValue, olValue) {
        if (newValue.length < 1) {
          this.totalScore = 0;
        }
      },
      deep: true
    },
    courseNameList: {
      handler: function(newValue, olValue) {
        this.ruleDataList = JSON.parse(JSON.stringify(newValue));
      },
      deep: true
    },
    // 深度监听触发
    listeningTrigger(newValue) {
      this.ruleDataList = JSON.parse(JSON.stringify(this.courseNameList));
      if (this.ruleDataList.length > 0) {
        this.getPaperScore();
      }
    }
  },
  methods: {
    getKnowledgeShow(list,index) {
      this.treeList = list.ruleKnowledgeList;
      this.knowList = list.knowledgeIds ? list.knowledgeIds.split(',') : [];
      this.knowledgeList = list.ruleKnowledgeList;
      this.knowledgeIndex = index;
      this.knowledgeShow = true;
    },
    // 总分计算
    getPaperScore() {
      let totalScore = 0;
      for (let j = 0; j < this.ruleDataList.length; j++) {
        if (this.ruleDataList[j].data == undefined) {
          return false;
        }
        for (let i = 0; i < this.ruleDataList[j].data.length; i++) {
          totalScore = totalScore + this.ruleDataList[j].data[i].total;
          this.ruleDataList[j].data[i].defficultys = this.ruleDataList[j].defficultys.toString();
          this.ruleDataList[j].data[i].onLineKnowledgeTitles = this.ruleDataList[j].knowledgeTitles;
          this.ruleDataList[j].data[i].onLineKnowledgeIds = this.ruleDataList[j].knowledgeIds.toString();
          this.ruleDataList[j].data[i].courseId = this.ruleDataList[j].Id;
        }
      }
      this.totalScore = totalScore;
      if (this.examScore !== null && this.totalScore > this.examScore) {
        return this.$message.error('考试总分必须是' + this.examScore + '分');
      }
    },
    // 计算每题分数
    onChangeNumber(value, index, parentId) {
      debugger
      let ruleIndex = this.courseId.indexOf(parentId);
      this.ruleDataList[ruleIndex].data[index].randomQuesNumber = value;
      this.ruleDataList[ruleIndex].data[index].total =
        (value * (this.ruleDataList[ruleIndex].data[index].randomQuesScore * 10000)) / 10000;
      this.getPaperScore();
    },
    // 分数改变是触发
    onChangeScore(value, index, parentId) {
      let ruleIndex = this.courseId.indexOf(parentId);
      this.ruleDataList[ruleIndex].data[index].randomQuesScore = value;
      this.ruleDataList[ruleIndex].data[index].total =
        (value * 10000 * this.ruleDataList[ruleIndex].data[index].randomQuesNumber) / 10000;
      this.getPaperScore();
    },
    // 难度 || 知识点修改
    onChangeState(list, index) {
      if (this.totalScore > 0) {
        this.temporaryList = list;
        this.temporaryIndex = index;
        return (this.visible = true);
      }
      this.$emit('onChangeCondition', list.Id, index, list);
    },
    // 知识点选择确定
    onChangeKnowledge() {
      var list = this.ruleDataList[this.knowledgeIndex];
      list.knowledgeIds = this.$refs.tree.ids ? this.$refs.tree.ids.join(',') : '';
      this.ruleDataList[this.knowledgeIndex].ruleKnowledgeList = list.knowledgeIds;
      var index = this.knowledgeIndex;
      if (this.totalScore > 0) {
        this.temporaryList = list;
        this.temporaryIndex = index;
        return (this.visible = true);
      };
      this.$emit('onChangeCondition', list.Id, index, list);
      this.cancelKnowledge();
    },
    cancelKnowledge() {
      this.treeList = [];
      this.knowList = [];
      this.knowledgeShow = false;
    },
    // 确认提示
    onHintOk() {
      if (this.temporaryIndex !== null) {
        this.$emit('onChangeCondition', this.temporaryList.Id, this.temporaryIndex, this.temporaryList);
        this.visible = false;
        this.cancelKnowledge();
      }
    },
    //保存
    onSave() {
      if (this.totalScore > 0) {
        if (this.examScore !== null && this.totalScore !== this.examScore) {
          return this.$message.error('考试总分必须是' + this.examScore + '分');
        }
      } else {
        return this.$message.error('考试总分必须大于 0 分');
      }
      this.getPaperScore();
      let jsonData = [];
      for (let j = 0; j < this.ruleDataList.length; j++) {
        jsonData = jsonData.concat(this.ruleDataList[j].data);
      }
      let quesJson = this.trimSpace(jsonData);
      this.$emit('onSave', JSON.stringify(quesJson), this.paperNumber);
    },
    onCancel() {
      this.$emit('onCancel');
    },
    // 去除数组中为选题为空的对象
    trimSpace(array) {
      for (var i = 0; i < array.length; i++) {
        if (array[i].randomQuesNumber < 1 || array[i].randomQuesScore <= 0) {
          array.splice(i, 1);
          i = i - 1;
        }
      }
      return array;
    }
  }
};
</script>

<style></style>
